﻿Ext.Loader.setConfig({
            enabled : true
        });
Ext.Loader.setPath('Ext.i18n', ctx+'/resources/extjs/i18n');
Ext.require('Ext.i18n.Bundle', function(){
	Ext.i18n.appBundle = Ext.create('Ext.i18n.Bundle',{
		bundle: 'Application',
		lang: 'en-US',
		path: 'resources/data',
		noCache: true
	});
});
var Share = {};
Ext.namespace("ChangeSystem");
ChangeSystem.OpenChange = 1;  //1 = 开启系统切换，0 = 禁用系统切换
/**
 * Ajax请求方法
 * 
 * @param {Object}
 *            settings.params 参数对象，必须
 * @param {String}
 *            settings.url 请求地址，必须
 * @param {Function}
 *            settings.callback 成功后回调方法，必须
 * @param {boolean}
 *            settings.showMsg 处理成功时，是否显示提示信息 true:显示 false:不显示
 * @param {boolean}
 *            settings.showWaiting 是否显示等待条 true:显示 false:不显示
 * @param {Number}
 *            settings.timeout 超时时间
 * @param {String}
 *            settings.successMsg 成功消息
 * @param {String}
 *            settings.failureMsg 失败消息
 */
/**
 * Call once at beginning to ensure your app can safely call console.log() and
 * console.dir(), even on browsers that don't support it.  You may not get useful
 * logging on those browers, but at least you won't generate errors.
 * 
 * @param  alertFallback - if 'true', all logs become alerts, if necessary. 
 *   (not usually suitable for production)
 */
Share.fixConsole = function (alertFallback)
{    
    if (typeof console === "undefined")
    {
        console = {}; // define it if it doesn't exist already
    }
    if (typeof console.log === "undefined") 
    {
        if (alertFallback) { console.log = function(msg) { alert(msg); }; } 
        else { console.log = function() {}; }
    }
    if (typeof console.dir === "undefined") 
    {
        if (alertFallback) 
        { 
            // THIS COULD BE IMPROVED… maybe list all the object properties?
            console.dir = function(obj) { alert("DIR: "+obj); }; 
        }
        else { console.dir = function() {}; }
    }
};

Share.AjaxRequest = function(settings) {
    // 参数对象
    var params = settings.params === undefined ? {} : settings.params,
        showWaiting = settings.showWaiting === undefined ? true : settings.showWaiting,
        showMsg = settings.showMsg === undefined ? true : settings.showMsg,
        timeout = settings.timeout === undefined ? 10*60*1000 : settings.timeout,
        // 发送请求
        waiting = null;
        
    if (showWaiting) {
        waiting = Ext.Msg.wait(Share.T('正在处理，请稍等...'), '', '');
    }
    Ext.Ajax.request({
                url     : settings.url,
                params  : params,
                timeout : timeout,
                success : function(response, options) {
                    if (waiting != null) {
                        waiting.hide();
                    }
                    var json = Ext.decode(response.responseText);
                    if (json.success == true) {
                        if (showMsg == true) { // 显示提示信息
                            // 请求成功时的提示文字
                            var successMsg = '操作成功.';
                            if (json.msg && json.msg != '') {
                                successMsg = json.msg;
                            }
                            else if (settings.successMsg && settings.successMsg != '') {
                                successMsg = settings.successMsg;
                            }
                            Ext.Msg.alert(Share.T('提示'), Share.T(successMsg), function() {
                                        if (settings.callback) { // 回调方法
                                            settings.callback(json);
                                        }
                                    });
                        }
                        else {
                            if (settings.callback) { // 回调方法
                                settings.callback(json);
                            }
                        }
                    }
                    else if (json.success == false) {
                        var message = '发生异常.';
                        if (json.msg && json.msg != '') { // 后台设定的业务消息
                            message = json.msg;
                        }
                        else if (settings.failureMsg && settings.failureMsg != '') { // 前台指定的错误信息
                            message = settings.failureMsg;
                        }
                        if (json.exceptionMessage && json.exceptionMessage != '') { // 有异常信息
                            Share.ExceptionWindow(message, json.exceptionMessage);
                        }
                        else {
                            Ext.Msg.alert(Share.T('错误'), Share.T(message), function() {
                                        if (typeof settings.falseFun == "function") { // 失败后想做的个性化操作函数
                                            settings.falseFun(json);
                                        }
                                    });
                        }
                    }
                    else if (typeof response.getResponseHeader == "function") {
                        // 得到response里面的头信息
                        // response.setHeader("session-status","timeout");
                        var sessionStatus = response.getResponseHeader("session-status");
                        if (sessionStatus == "timeout") { // timeout
                            Ext.Msg.alert(Share.T('提示'), '<span style="color:red"><b>'+Share.T('登录超时,请重新登录!')+'</b></span>', function() {
                                        Share.getWin().location = ctx;
                                    });
                            return false;
                        }
                        // 服务器出错
                        if (sessionStatus == "pagenotfind") { // pagenotfind
                            Ext.Msg.alert(Share.T('提示'), '<span style="color:red"><b>'+Share.T('很抱歉，您要访问的页面不存在！')+'</b></span>',

                            function() {
                                    });
                            return false;
                        }
                        if (settings.callback) { // 回调方法
                            settings.callback(json);
                        }
                    }
                },
                failure : function(response, options) {
                    if (waiting != null) {
                        waiting.hide();
                    }
                    Share.ExceptionWindow(Share.T('错误')+':' + response.status + ' ' + response.statusText, response.responseText);
                }
            });
};

/**
 * 显示异常信息的窗口
 * 
 * @param message
 *            异常信息
 * @param exceptionMsg
 *            异常详细信息
 */
Share.ExceptionWindow = function(message, exceptionMessage) {
    var _message = message === undefined ? '发生异常!' : message == '' ? '发生异常!' : message,
        _exceptionMessage = exceptionMessage === undefined ? '发生异常!' : exceptionMessage == ''
                ? '发生异常!'
                : exceptionMessage,
        _exceptionWindow = Ext.getCmp('_exceptionWindow');
    if (!_exceptionWindow) {
        _exceptionWindow = new Ext.Window({
                    id         : '_exceptionWindow',
                    title      : Share.T('错误'),
                    width      : 400,
                    autoHeight : true,
                    modal      : true,
                    layout     : 'fit',
                    items      : [new Ext.form.Label({
                                        html : '<div style="padding:5px;">' + _message + '</div>'
                                    }), new Ext.Panel({
                                        title       : Share.T('详细信息'),
                                        // bodyStyle:'overflow-x:visible;overflow-y:scroll;',
                                        // bodyStyle:'overflow-x:hidden;;overflow-y:scroll;',
                                        collapsible : true,
                                        collapsed   : true,
                                        autoScroll  : true,
                                        height      : 200,
                                        html        : _exceptionMessage
                                    })]
                }).show();
    }
    else {
        _exceptionWindow.show();
    }
};

/**
 * map转数组。
 * 
 * @param {Map}map
 *            map对象
 * @return 数组
 */
Share.map2Ary = function(map) {
    var list = [];
    for (var key in map) {
        list.push([key, map[key]]);
    }
    return list;
};

/**
 * 获取map中的值。
 * 
 * @param {String}value
 *            要渲染的值
 * @param {Map}mapping
 *            Map对象
 * @param {String}defaultText
 *            没有对应的key时的默认值
 * @return {String}对应的value值
 */
Share.map = function(value, mapping, defaultText) {
    return mapping[value] || (defaultText === undefined || defaultText === null ? value : defaultText);
};
/**
 * 设置系统主题
 */
Share.swapStyle = function(themeCss) {
    // Ext.state.Manager.setProvider(new Ext.state.CookieProvider());
    // 设置主题
    var theme = themeCss === undefined ? Ext.state.Manager.get('Cxjava_theme') : themeCss;
    if (theme && theme != '') {
        // 实际改变风格样式的处理
        Ext.util.CSS.swapStyleSheet('theme', ctx + '/resources/extjs/resources/css/' + theme);
        Ext.state.Manager.set('Cxjava_theme', theme);
    }
    else {
        Ext.util.CSS.swapStyleSheet('theme', ctx + '/resources/extjs/resources/css/ext-all-gray.css');
        Ext.state.Manager.set('Cxjava_theme', 'ext-all-gray.css');
    }
};

Share.opentTabByPanel = function(node, panelAlias, isLoad, status) {

    if (!panelAlias) return null;

    var id = 'tab-' + node.data.id;
//    if(id=='tab-set-importfile'){  //new 2013.4.23  备用：文件导入设置TAB被切换后的动作
//    	if(Ext.getCmp('share-new-address')){
//    		Ext.getCmp('share-new-address').setValue('1');
//    	}
//    }else{
//    	if(Ext.getCmp('share-new-address')){
//        	Ext.getCmp('share-new-address').setValue('0');
//    	}
//    }
//    if(Ext.getCmp('share-new-address')){
//    	if(Ext.getCmp('share-new-address').getValue() != '1'){
//        	//当当前TAB不是文件导入设置时，将触发的动作
//        }
//    }
//    console.log(id);
    var title = node.data.text;
    var iconCls = node.data.iconCls;

    var tabPanel = Ext.getCmp('centertabpanel');
    var tab = tabPanel.getComponent(id);

    // 参数验证
    if (!tabPanel || title == "" || id == "") {
        Ext.Msg.alert(Share.T('错误'), Share.T("参数错误."), function() {
                    return false;
                });
        return null;
    }

    if (!tab) {
    	
        var newPanel = Ext.create(panelAlias, {
            id         : id,
            title      : title,
            iconCls    : iconCls,
            closable   : true,
            autoScroll : true
                // layout : 'fit'
            }
        );
        if (newPanel) {
            tab = tabPanel.add(newPanel).show();
//            console.log(tab);
            if(id == 'tab-deal-enter'){//解决tab切换重复load问题
            	Share.enterFlag = true;
            }
            if (tab.store && !isLoad) {
                tab.store.currentPage = 1;
                //获取类中的所有属性
                var str = "var obj={";
                var params = tab.store.proxy.extraParams;
                for(items in params){
                	//将所有属性设置为null
                	str += items+":null,";
                }
                str +="error:null}";
                eval(str);//执行这段String类型
                tab.store.on("beforeload",function(store){
                 //将类中的所有属性设置为null类型 解决关tab之后再次重新打开tab 依旧按照原来的查询参数查询数据问题
               	 Ext.apply(store.proxy.extraParams , obj); 
                });
                tab.store.load({ params: { page: 1, start: 0} });
            }
            // tabPanel.setActiveTab(tab);
            // tabPanel.doLayout();

            // 限制最多能开10个tab
            if (tabPanel.items.length > 10) {
                var firstTab = tabPanel.getComponent(tabPanel.items.items[1]);
                if (firstTab) {
                    tabPanel.remove(firstTab);
                }
            }
        }
    } else {
    	if(status){
    		Ext.ComponentMgr.get("voucher_btn_status").setValue(status);
    	}
    	tabPanel.setActiveTab(tab);
    }
    if(id=="tab-import-file"){//new 2013.4.23：添加本地文件标题设置完后重新选择TAB(文件导入)窗口后，进行同步刷新并自动return值。
    	Share.AjaxRequest({
            url      : ctx + '/getLabelName',
            showMsg: false,
            params   : {
            },
            callback : function(json) {
//          	  console.log(json);
          	  if(json.data != "" || json.data != null){
          		  if(!(json.data[0].t1 == "" || json.data[0].t1 == null)){
          			  Ext.getCmp('file-title1-tax').setText(Share.T(json.data[0].t1));
          		  }else{
          			Ext.getCmp('file-title1-tax').setText(Share.T("文件一"));
          		  }
          		  if(!(json.data[0].t2 == "" || json.data[0].t2 == null)){
          			Ext.getCmp('file-title2-tax').setText(Share.T(json.data[0].t2));
          		  }else{
          			Ext.getCmp('file-title2-tax').setText(Share.T("文件二"));
          		  }
          		  if(!(json.data[0].t3 == "" || json.data[0].t3 == null)){
          			Ext.getCmp('file-title3-tax').setText(Share.T(json.data[0].t3));
          		  }else{
          			Ext.getCmp('file-title3-tax').setText(Share.T("文件三"));
          		  }
          		  if(!(json.data[0].t4 == "" || json.data[0].t4 == null)){
          			Ext.getCmp('file-title4-tax').setText(Share.T(json.data[0].t4));
          		  }else{
          			Ext.getCmp('file-title4-tax').setText(Share.T("文件四"));
          		  }
          	  	  if(!(json.data[0].t5 == "" || json.data[0].t5 == null)){
          	  		Ext.getCmp('file-title5-tax').setText(Share.T(json.data[0].t5));
          	  	  }else{
          	  		Ext.getCmp('file-title5-tax').setText(Share.T("文件五"));
          	  	  }
          	  }
            }
        });
    	return tab;
    }
    return tab;
};

/**
 * 打开tab
 * 
 * @param {Object}node
 *            结点对象
 * @param {String}url
 *            链接
 * @param {String}iconCls
 *            样式
 */
Share.opentTabByURL = function(node, url) {
    var id = node.data.text;
    var title = node.data.text;
    var iconCls = node.data.iconCls;

    var tabPanel = Ext.getCmp('centertabpanel');
    var tab = tabPanel.getComponent(id);

    // 参数验证
    if (!tabPanel || title == "" || url == "" || id == "") {
        Ext.Msg.alert(Share.T('错误'), Share.T("参数错误."), function() {
                    return false;
                });
        return;
    }

    var url = encodeURI(encodeURI(url), autoLoad = {
                url        : url,
                params     : {
                    id : id + "_div"
                },
                method     : "GET",
                scripts    : true,
                scope      : this,
                nocache    : true,
                discardUrl : true,
                text       : Share.T('加载中,请稍候...'),
                timeout    : 3000
            });

    if (!tab) {
        var newTab = {
            id         : id,
            title      : title,
            iconCls    : iconCls,
            closable   : true,
            autoScroll : true,
            autoLoad   : autoLoad,
            listeners  : {
                activate : function(Panel) {
                    // 自动调节高度和宽度
                    var inPanel = Ext.getCmp(Panel.id + "_div_panel");
                    if (inPanel) {
                        inPanel.doLayout(true, true);
                        inPanel.setHeight(index.tabPanel.getInnerHeight() - 1);
                        inPanel.setWidth(Panel.getWidth());
                    }
                }
            }
        };

        tabPanel.add(newTab).show();
        // 限制最多能开10个tab
        if (tabPanel.items.length > 10) {
            var firstTab = tabPanel.getComponent(tabPanel.items.items[1]);
            if (firstTab) {
                tabPanel.remove(firstTab);
            }
        }
    }
    else {
        // tab页已经存在的场合
        // tab.getUpdater().update(autoLoad);
        tabPanel.setActiveTab(tab);
    }
};

/** 得到最顶层的window对象 */
Share.getWin = function() {
    var win = window;
    while (win != win.parent) {
        win = win.parent;
    }
    return win;
};

/** 清空选择的grid */
Share.resetGrid = function(grid) {
    // 清空选中的记录
    grid.getSelectionModel().clearSelections();
    grid.getEl().select('div.x-grid3-hd-checker').removeClass('x-grid3-hd-checker-on');
};

/** 问候 */
Share.sayHello = function() {
    var hour = new Date().getHours(),
        hello = '';
    if (hour < 6) {
        hello = Share.T('凌晨好');
    }
    else if (hour < 9) {
        hello = Share.T('早上好');
    }
    else if (hour < 12) {
        hello = Share.T('上午好');
    }
    else if (hour < 14) {
        hello = Share.T('中午好');
    }
    else if (hour < 17) {
        hello = Share.T('下午好');
    }
    else if (hour < 19) {
        hello = Share.T('傍晚好');
    }
    else if (hour < 22) {
        hello = Share.T('晚上好');
    }
    else {
        hello = Share.T('夜里好');
    }
    return hello + '！';
};

/**
 * 扩展基础类 判断以什么结尾
 */
String.prototype.endsWith = function(suffix) {
    return this.indexOf(suffix, this.length - suffix.length) !== -1;
};

/**
 * 扩展基础类 得到字符串的长度，包括中文和英文
 */
String.prototype.charlen = function() {
    var arr = this.match(/[^\x00-\xff]/ig);
    return this.length + (arr == null ? 0 : arr.length);
};

/**
 * 扩展基础类 字符串首尾去空格
 */
String.prototype.trim = function() {
    return this.replace(/(^\s*)|(\s*$)/g, "");
};

/**
 * 扩展基础类 字符串包含字符串判断
 */
String.prototype.contains = function(sub) {
    return this.indexOf(sub) != -1;
};

Share.Msg = function() {
    var msgCt;

    function createBox(t, s) {
        // return ['<div class="msg">',
        // '<div class="x-box-tl"><div class="x-box-tr"><div
        // class="x-box-tc"></div></div></div>',
        // '<div class="x-box-ml"><div class="x-box-mr"><div
        // class="x-box-mc"><h3>', t, '</h3>', s, '</div></div></div>',
        // '<div class="x-box-bl"><div class="x-box-br"><div
        // class="x-box-bc"></div></div></div>',
        // '</div>'].join('');
        return '<div class="msg"><h3>' + t + '</h3><p>' + s + '</p></div>';
    }
    return {
        msg  : function(title, format) {
            if (!msgCt) {
                msgCt = Ext.DomHelper.insertFirst(document.body, {
                            id : 'msg-div'
                        }, true);
            }
            var s = Ext.String.format.apply(String, Array.prototype.slice.call(arguments, 1));
            var m = Ext.DomHelper.append(msgCt, createBox(title, s), true);
            m.hide();
            m.slideIn('t').ghost("t", {
                        delay  : 1000,
                        remove : true
                    });
        },

        init : function() {
            // var t = Ext.get('exttheme');
            // if(!t){ // run locally?
            // return;
            // }
            // var theme = Cookies.get('exttheme') || 'aero';
            // if(theme){
            // t.dom.value = theme;
            // Ext.getBody().addClass('x-'+theme);
            // }
            // t.on('change', function(){
            // Cookies.set('exttheme', t.getValue());
            // setTimeout(function(){
            // window.location.reload();
            // }, 250);
            // });
            //
            // var lb = Ext.get('lib-bar');
            // if(lb){
            // lb.show();
            // }
        }
    };
}();

Share.createPanelByAlias = function(aliasName) {
    var panelid = 'panel-' + aliasName.split('.')[1];
//    console.log(panelid);

    var cmp = Ext.getCmp(panelid);
    if (cmp) {
        return cmp;
    }
    else {
        return Ext.create(aliasName, {
                    id : panelid
                });
    }
};

Share.showPanelAsWindow = function(panel, model, y) {
    var winid = 'win-' + Ext.ClassManager.getAliasesByName(Ext.ClassManager.getName(panel))[0].split('.')[1];
   // console.log(winid);

    var cmp = Ext.getCmp(winid);
    if (cmp) {
        Ext.WindowManager.bringToFront(cmp);
        return;
    }

    var win = Ext.create('Ext.window.Window', {
                id        : winid,
                title     : panel.title,
                resizable : true,
                closable  : true,
                width     : panel.width,
                minWidth  : 300,
                minHeight : panel.id.substring(0,17) == 'panel-importlocal' || panel.id.substring(0,17) == 'panel-importserve' ? 31 : 220,
                modal     : model === undefined ? false : model,
                y         : y === undefined ? y : panel.id.substring(0,17) == "panel-mdataclient" ? 60 : panel.id.substring(0,17) == "panel-importlocal" ? 60 : winid.substring(0,17) == 'win-setdatasource' ? 60 : 180,
                layout    : 'fit',
                plain     : true,
                modal :true,
                items     : panel, // your form or fields would
                // go here
                buttons   : [{
                            text    : Share.T('保存'),
                            hidden : winid == 'win-setplangrid'|winid == 'win-setdatasourceviewpanel'|winid == 'win-serverfilewin'|winid == 'win-editioninfowin'  ? true : false,
                            handler : function() {
                                // console.log(HIT);
                                // console.log(ldAPP);

                                var controller = {};
                                var panleClassName = '';
                                if (panel) {
                                	if(winid == 'win-dealstateopenpanel'){
                                		Ext.getCmp('dealsearch-choose-value').setValue('panel-dealstateopenpanel');  //置为已开
                                	}else if(winid == 'win-splitmanualparampanel'){
                                		Ext.getCmp('dealsearch-choose-value').setValue('panel-splitmanualparampanel'); //手动拆分
                                	}
                                    panleClassName = Ext.ClassManager.getName(panel).split('.')[2];
                                    // console.log(panleClassName);

                                    for (var c in HIT.controller) {
                                        var ctl = ldAPP.getController(c);
                                        // console.log(ctl);

                                        for (var v in ctl.views) {
                                            // console.log(ctl.views[v]);
                                            // console.log(ldAPP.getView(ctl.views[v]).create());
                                            if (ctl.views[v] == panleClassName) {
                                                controller = ctl;
                                           //     console.log(controller);
                                                if (controller && typeof(controller.save) == 'function') {
                                                    controller.save(win);
                                                }

                                                break;
                                            }
                                        }
                                    }
                                }
                            }
                        }, {
                            text    : winid == 'win-editioninfowin' ? Share.T('确定') : Share.T('取消'),
                            hidden:winid == 'win-serverfilewin' ? true : false,
                            handler : function() {
                                win.close();
                            }
                        }]
            }).show();

};


Share.showPanelAsViewWindow = function(panel, model) {
    var winid = 'win-' + Ext.ClassManager.getAliasesByName(Ext.ClassManager.getName(panel))[0].split('.')[1];
//    console.log(winid);

    var cmp = Ext.getCmp(winid);
    if (cmp) {
        Ext.WindowManager.bringToFront(cmp);
        return;
    }

    var win = Ext.create('Ext.window.Window', {
                id        : winid,
                title     : panel.title,
                resizable : true,
                closable  : true,
                width     : panel.width,
                minWidth  : 300,
                minHeight : 200,
                modal     : model === undefined ? false : model,
                y         : panel.id.substring(0,17) == "panel-mdataclient" ? 60 : 150,
                layout    : 'fit',
                plain     : true,
                items     : panel, // your form or fields would
                // go here
                buttons   : [{
                            text    : Share.T('取消'),
                            handler : function() {
                                win.close();
                            }
                        }]
            }).show();

};

Share.showWindow = function(win, model) {
    win.modal = model === undefined ? false : model;

    win.show();
};

Share.fmoney = function(s, n) {
    if (s == null || s == '') return '';
    n = n > 0 && n <= 20 ? n : 2;
    s = parseFloat((s + "").replace(/[^\d\.-]/g, "")).toFixed(n) + "";
    var l = s.split(".")[0].split("").reverse(),
        r = s.split(".")[1];
    t = "";
    for (i = 0; i < l.length; i++) {
        t += l[i] + ((i + 1) % 3 == 0 && (i + 1) != l.length ? "," : "");
    }
    return t.split("").reverse().join("") + "." + r;
};

Share.RetainDecimal = function(value,n){
	n = n=== undefined ? 2 : n;
	var num = new Number(value);
	return num.toFixed(n);
	
	// return (Math.round(value*100)/100);
};

Share.rmoney = function(s) {
    return parseFloat(s.replace(/[^\d\.-]/g, ""));
};

Share.loadLeftTree = function(o) {
    Share.leftTreeData = {};
    this.AjaxRequest({
                url      : ctx + '/getLeftList',
                params   : {
                    centerName : null
                },
                showMsg  : false,
                callback : function(json) {
                    Share.leftTreeData = json;
                    
                    var rootNode = Share.getLeftTree('left-import');
                    if (rootNode) {
                        o.getStore('LeftTree').setRootNode(rootNode);
                    }
                }
            });
};

Share.getLeftTree = function(buttonId) {
    for (var i = 0; i < Share.leftTreeData.data.length; i++) {
        if (Share.leftTreeData.data[i].centerName == buttonId) {
            return Ext.clone(Share.leftTreeData.data[i]);
        }
    }
    return [];
};

Share.checkCreatorFromGroupId = function(){
	Share.check ;
	this. AjaxRequest({                 
		 url      : ctx + '/checkCreatorFromGroupId',
         params: {         	
         },
         showMsg  : false,
         showWaiting : false,
         callback: function (json) {
            	if(json.resultcode == '0'){           		
             	   Share.check = true;
            	}else if(json.resultcode == '2'){          		
            		Share.check = false;             		
            	}
         }       
     });		
},
Share.checkFun = function(){	
	return Share.check;
},

Share.Ref = [];
Share.getRef = function(){	
	this. AjaxRequest({                 
		 url      : ctx + '/getRef',
        params: {         	
        },
        showMsg  : false,
        showWaiting : false,
        callback: function (json) {
        	if(json.success){
        	   Share.Ref = json.data;
        	}
        	for(var i = 0; i < Share.Ref.length; i++){
        		Share.Ref[i] = Share.T(Share.Ref[i]);
        	}
        }       
    });
},

Share.T = function(key) {	//国际化
	var language = Ext.state.Manager.get('Cxjava_lang') == "en" ? "en-US" : "zh-CN";
	if(language == "zh-CN"){
		return key;
		 }else{
	//	Ext.i18n.appBundle.onReady(function(){
           return  Ext.i18n.appBundle.getMsg(key); 
			
	//	});
	}
 //	return key;
};
Share.documentNo="";//暂存单据号
Share.enterFlag = false;//标志“票据录入”tab是否已经打开，false:未打开
//Share.selectRows = [];//存放已选择的grid行
//获取票据类型设置信息
Share.getInvoiceInitConfig = function(){
	this.AjaxRequest({
        url      : ctx + '/getInvoiceInitConfig',
        params   : {},
        showMsg  : false,
        callback : function(json) {
        	if(json.success){
        		Share.InvoiceConfig = json.data;
         	}
        }
    });
};

//根据发票类型获取发票config
Share.invoiceInitConfig = function(code){
	for (var i = 0; i < Share.InvoiceConfig.length; i++) {
        if (Share.InvoiceConfig[i].DOC_TYPE_CODE == code) {
            return Ext.clone(Share.InvoiceConfig[i]);
        }
    }
	return null;
};

/*
 *    发票信息：Share.InvoiceConfig.DOC_TYPE_CODE(类型代码)
 *                   Share.InvoiceConfig.PRICE_WAY（计价方式）
 */
Share.InvoiceConfig= {};



//修改英文界面emptytext做为参数传递到后台的情况
if(Ext.supports.Placeholder != true){

	
	Ext.define('patches.TextFieldEmptyText', {
		override:'Ext.form.field.Text',

		initComponent:function(){
			
			//修改ie8中文本框下边栏不显示的问题，
			if(this.xtype == 'textfield'){
				Ext.apply(this, {
					height: 23
				});
			}
			
			if(this.emptyText) {
				Ext.apply(this, {
					_emptyText:this.emptyText,
					emptyText:null,
					enableKeyEvents:true
				});
				this.on({
					scope:this,
					focus:this._handleEmptyText,
					blur:this._handleEmptyText,
					change:this._handleEmptyText
				});
			}

			this.callParent();
		},

		onRender:function(){
			this.callParent();
			if(this._emptyText) {
				this._emptyTextEl = Ext.DomHelper.insertBefore(this.inputEl, {
					cls:this.emptyCls,
					style:'position:absolute;' +  //The element must be relative to cover the input element;
						'overflow: hidden;' +
						'padding-left: 2px;' +
						//'padding-top: 1px;' +
						'padding-right: 0.8px;' +
						'white-space:nowrap;' +
						'line-height: ' + this.getHeight() + 'px;' +
						'z-index: 100;' +
						//'word-break:break-all;' +
	                    //'height:15px;' + // The element must be without height to not affect layout
	                    'pointer-events:none;', // optimization for supporting browsers
	                html:this._emptyText
	            }, true);
				this.mon(this._emptyTextEl, 'click', function(){
	                this.focus(false, 0);
	            }, this);
				this._handleEmptyText();
	        }
	    },

	    _handleEmptyText:function(){
	        if(!this.rendered || !this._emptyTextEl) return;
	        var rawValue = this.getRawValue(),
	            isEmpty = (!rawValue.length);
	        if(isEmpty) {
	            this._emptyTextEl.show();

//	            if(this.hasFocus) {
//	                this._emptyTextEl.addCls(this.emptyTextFocusedCls);
//	            } else {
//	                this._emptyTextEl.removeCls(this.emptyTextFocusedCls);
//	            }
	        } else {
	            this._emptyTextEl.hide();
	        }
	    }
	});
}


//修改下拉框传值问题
Share.changeCombox = function(str){
	var value = str;
	switch(str){
		case "All":
			value = 101;
			break;
		case "Invoice has been drawn":
			value = 0;
			break;
		case "It has been set off":
			value = 5;
			break;
		case "Write back":
			value = 9;
			break;
		case "All status":
			value = 0;
			break;
		case "Abolished":
			value = 1;
			break;
		case "Red instrument":
			value = 2;
			break;
		case "Split/merge":
			value = 0;
			break;
		case "Not split/merged":
			value = 1;
			break;
		case "Split":
			value = 2;
			break;
		case "Consolidated":
			value = 3;
			break;
		case "Status of all instruments":
			value = -1;
			break;
		case "The invoice has not been drawn":
			value = 0;
			break;
		case "Printing":
			value = 2;
			break;
		case "Reviewed":
			value = 3;
			break;
		case "Exported":
			value = 4;
			break;
		case "Associated":
			value = 8;
			break;
		case "Hold":
			value = 10;
			break;
	}
	return value;
};

//修改下拉框传值问题
Share.SearchCombox = function(str){
	var value = str;
	switch(str){
		case "Status of all instruments":
			value = -1;
			break;
		case "The invoice has not been drawn":
			value = 0;
			break;
		case "Invoice has been drawn":
			value = 1;
			break;
		case "Printing":
			value = 2;
			break;
		case "Reviewed":
			value = 3;
			break;
		case "Exported":
			value = 4;
			break;
		case "Associated":
			value = 8;
			break;
		case "Write back":
			value = 9;
			break;
		case "Hold":
			value = 10;
			break;
	}
	return value;
};

/**
 * 系统message调用方法
 * 
 * msgCode 	调用的message代码
 * param1 	参数1
 * param2	参数2
 * param3	参数3
 * param4	参数4
 * param5	参数5
 */
Share.ShowMessage = function(msgCode,param1,param2,param3,param4,param5) {
	//取出msgCode首位字母判断提示类型：E 错误，I 提示
	var type = msgCode.substring(0, 1);
	// show message
	var message = '';
	// 请求json数据，获取所有message，赋值给MessageAll
	Ext.Ajax.request({
		url : 'resources/data/Message.json',
		success : function(response, options) {
			var MessageAll = Ext.decode(response.responseText);
			for ( var i = 0; i < MessageAll.length; i++) {
				if (MessageAll[i].code == msgCode) {
					message = MessageAll[i].msg;
					if(message.contains("{0}")){
						message = message.replace("{0}",param1);
					}
					if(message.contains('{1}')){
						message = message.replace('{1}',param2);
					}
					if(message.contains('{2}')){
						message = message.replace('{2}',param3);
					}
					if(message.contains('{3}')){
						message = message.replace('{3}',param4);
					}
					if(message.contains('{4}')){
						message = message.replace('{4}',param5);
					}
					if (type == 'E') {// 错误信息
						Ext.Msg.alert(Share.T('错误'), Share.T(message));
						break;
					} else if (type == 'C'){// 确认信息
						return message;
					} else if (type == 'I') {// 提示信息
						Ext.Msg.alert(Share.T('提示'), Share.T(message));
						break;
					}
				}
			}
		}
	});
};

Share.showMsg=function(type,msg1,msg2,value){
	var message1 = '';
	var message2 = '';
	var val = value;
	Ext.Ajax.request({
		url : 'resources/data/Message.json',
		success : function(response, options) {
			var MessageAll = Ext.decode(response.responseText);
			for ( var i = 0; i < MessageAll.length; i++) {
				if (MessageAll[i].code == msg1) {
					message1 = MessageAll[i].msg;
				}
				else if(MessageAll[i].code == msg2){
					message2 = MessageAll[i].msg;
				}
				if(message1 !='' && message2 !=''){
					break;
				}
			}
			if (type == 'E') {// 错误信息
				Ext.Msg.alert(Share.T('错误'), Share.T(message1)+val+Share.T(message2));
			}else if (type == 'I') {// 提示信息
				Ext.Msg.alert(Share.T('提示'), Share.T(message1)+val+Share.T(message2));
			}	
		}
	});
};

// 复写文本框错误提示位置属性，防止某些忘记添加此功能出现的提示不正确
Ext.define('Ext.form.field.Text', {
	override:'Ext.form.field.Text',
	initComponent: function () {
		if(this.msgTarget == 'title'){
			Ext.apply(this, {
				msgTarget : 'side'
			});
		}
        this.callParent();
    }
});

//复写Rownumberer里的renderer属性（修改刷新后，每页的页码从1开始计数问题）
Ext.define('Ext.grid.RowNumberer', {
	override:'Ext.grid.RowNumberer',
	initComponent: function () {
			Ext.apply(this, {
				renderer: function(value, metaData, record, rowIdx, colIdx, store) {
			        if (this.rowspan){
			            metaData.cellAttr = 'rowspan="'+this.rowspan+'"';
			        }
			        metaData.tdCls = Ext.baseCSSPrefix + 'grid-cell-special';
			        var taxcurrentpage=store.currentPage-1;
					var taxpageSize=store.pageSize;
					taxcurPageSize=taxcurrentpage*taxpageSize;
					return taxcurPageSize+1+rowIdx;
			    }
			});
        this.callParent();
    }
});
